#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
供应商关系管理系统 (Supplier Relationship Management - SRM)

主要功能：
1. 供应商信息管理和分类
2. 供应商绩效评估和监控
3. 合同管理和续约提醒
4. 供应商风险评估和管理

作者: Assistant
日期: 2024
"""

import json
import csv
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Any, Tuple
from enum import Enum
from dataclasses import dataclass, asdict
import uuid
import statistics

class SupplierStatus(Enum):
    """供应商状态"""
    ACTIVE = "active"
    INACTIVE = "inactive"
    SUSPENDED = "suspended"
    BLACKLISTED = "blacklisted"
    UNDER_REVIEW = "under_review"

class SupplierCategory(Enum):
    """供应商分类"""
    STRATEGIC = "strategic"  # 战略供应商
    PREFERRED = "preferred"  # 优选供应商
    APPROVED = "approved"    # 合格供应商
    CONDITIONAL = "conditional"  # 条件供应商
    DEVELOPMENT = "development"  # 发展供应商

class RiskLevel(Enum):
    """风险等级"""
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"

class ContractStatus(Enum):
    """合同状态"""
    DRAFT = "draft"
    ACTIVE = "active"
    EXPIRED = "expired"
    TERMINATED = "terminated"
    RENEWED = "renewed"

class PerformanceMetric(Enum):
    """绩效指标"""
    QUALITY = "quality"
    DELIVERY = "delivery"
    COST = "cost"
    SERVICE = "service"
    INNOVATION = "innovation"
    SUSTAINABILITY = "sustainability"

@dataclass
class Supplier:
    """供应商信息"""
    supplier_id: str
    name: str
    contact_person: str
    email: str
    phone: str
    address: str
    country: str
    category: str
    status: str
    registration_date: datetime
    business_license: str
    tax_id: str
    bank_account: str
    payment_terms: str
    credit_rating: str
    annual_revenue: float
    employee_count: int
    certifications: List[str]
    products_services: List[str]
    website: str = ""
    notes: str = ""
    last_updated: datetime = None
    
    def __post_init__(self):
        if self.last_updated is None:
            self.last_updated = datetime.now()

@dataclass
class Contract:
    """合同信息"""
    contract_id: str
    supplier_id: str
    contract_name: str
    contract_type: str
    start_date: datetime
    end_date: datetime
    contract_value: float
    currency: str
    status: str
    payment_terms: str
    delivery_terms: str
    quality_requirements: str
    penalty_clauses: str
    renewal_terms: str
    created_date: datetime
    created_by: str
    file_path: str = ""
    notes: str = ""
    auto_renewal: bool = False
    renewal_notice_days: int = 30
    
    def __post_init__(self):
        if self.created_date is None:
            self.created_date = datetime.now()

@dataclass
class PerformanceRecord:
    """绩效记录"""
    record_id: str
    supplier_id: str
    evaluation_period: str
    metric_type: str
    metric_value: float
    target_value: float
    unit: str
    score: float  # 0-100分
    comments: str
    evaluator: str
    evaluation_date: datetime
    supporting_data: Dict[str, Any]
    
    def __post_init__(self):
        if self.evaluation_date is None:
            self.evaluation_date = datetime.now()

@dataclass
class RiskAssessment:
    """风险评估"""
    assessment_id: str
    supplier_id: str
    risk_category: str
    risk_description: str
    risk_level: str
    probability: float  # 0-1
    impact: float  # 0-1
    risk_score: float  # probability * impact
    mitigation_measures: List[str]
    responsible_person: str
    assessment_date: datetime
    review_date: datetime
    status: str  # open, mitigated, closed
    
    def __post_init__(self):
        if self.assessment_date is None:
            self.assessment_date = datetime.now()
        if self.review_date is None:
            self.review_date = self.assessment_date + timedelta(days=90)
        self.risk_score = self.probability * self.impact

class SupplierRelationshipManager:
    """供应商关系管理系统"""
    
    def __init__(self):
        self.suppliers: Dict[str, Supplier] = {}
        self.contracts: Dict[str, Contract] = {}
        self.performance_records: List[PerformanceRecord] = []
        self.risk_assessments: List[RiskAssessment] = []
        self.evaluators: Dict[str, Dict[str, Any]] = {}
        
    def register_supplier(self, supplier_data: Dict[str, Any]) -> bool:
        """注册供应商"""
        try:
            supplier = Supplier(
                supplier_id=supplier_data['supplier_id'],
                name=supplier_data['name'],
                contact_person=supplier_data['contact_person'],
                email=supplier_data['email'],
                phone=supplier_data['phone'],
                address=supplier_data['address'],
                country=supplier_data['country'],
                category=supplier_data.get('category', SupplierCategory.APPROVED.value),
                status=supplier_data.get('status', SupplierStatus.ACTIVE.value),
                registration_date=supplier_data.get('registration_date', datetime.now()),
                business_license=supplier_data['business_license'],
                tax_id=supplier_data['tax_id'],
                bank_account=supplier_data.get('bank_account', ''),
                payment_terms=supplier_data.get('payment_terms', ''),
                credit_rating=supplier_data.get('credit_rating', ''),
                annual_revenue=supplier_data.get('annual_revenue', 0.0),
                employee_count=supplier_data.get('employee_count', 0),
                certifications=supplier_data.get('certifications', []),
                products_services=supplier_data.get('products_services', []),
                website=supplier_data.get('website', ''),
                notes=supplier_data.get('notes', '')
            )
            
            self.suppliers[supplier.supplier_id] = supplier
            return True
            
        except Exception as e:
            print(f"注册供应商失败: {e}")
            return False
    
    def update_supplier_info(self, supplier_id: str, update_data: Dict[str, Any]) -> bool:
        """更新供应商信息"""
        if supplier_id not in self.suppliers:
            return False
        
        try:
            supplier = self.suppliers[supplier_id]
            
            # 更新允许修改的字段
            updatable_fields = [
                'name', 'contact_person', 'email', 'phone', 'address',
                'category', 'status', 'payment_terms', 'credit_rating',
                'annual_revenue', 'employee_count', 'certifications',
                'products_services', 'website', 'notes'
            ]
            
            for field, value in update_data.items():
                if field in updatable_fields and hasattr(supplier, field):
                    setattr(supplier, field, value)
            
            supplier.last_updated = datetime.now()
            return True
            
        except Exception as e:
            print(f"更新供应商信息失败: {e}")
            return False
    
    def get_supplier_360_view(self, supplier_id: str) -> Dict[str, Any]:
        """获取供应商360度视图"""
        if supplier_id not in self.suppliers:
            return {'error': '供应商不存在'}
        
        supplier = self.suppliers[supplier_id]
        
        # 获取相关合同
        supplier_contracts = [
            contract for contract in self.contracts.values()
            if contract.supplier_id == supplier_id
        ]
        
        # 获取绩效记录
        supplier_performance = [
            record for record in self.performance_records
            if record.supplier_id == supplier_id
        ]
        
        # 获取风险评估
        supplier_risks = [
            risk for risk in self.risk_assessments
            if risk.supplier_id == supplier_id
        ]
        
        # 计算综合评分
        overall_score = self._calculate_overall_score(supplier_id)
        
        # 获取关键指标
        key_metrics = self._get_key_metrics(supplier_id)
        
        return {
            'supplier_info': asdict(supplier),
            'contracts': {
                'total_contracts': len(supplier_contracts),
                'active_contracts': len([c for c in supplier_contracts if c.status == ContractStatus.ACTIVE.value]),
                'total_value': sum(c.contract_value for c in supplier_contracts if c.status == ContractStatus.ACTIVE.value),
                'contracts': [asdict(c) for c in supplier_contracts]
            },
            'performance': {
                'total_evaluations': len(supplier_performance),
                'overall_score': overall_score,
                'key_metrics': key_metrics,
                'recent_records': [asdict(r) for r in supplier_performance[-5:]]
            },
            'risk_profile': {
                'total_risks': len(supplier_risks),
                'open_risks': len([r for r in supplier_risks if r.status == 'open']),
                'risk_level': self._get_overall_risk_level(supplier_id),
                'recent_assessments': [asdict(r) for r in supplier_risks[-3:]]
            },
            'recommendations': self._get_supplier_recommendations(supplier_id)
        }
    
    def register_evaluator(self, evaluator_data: Dict[str, Any]) -> bool:
        """注册评估员"""
        try:
            evaluator_id = evaluator_data['evaluator_id']
            self.evaluators[evaluator_id] = {
                'name': evaluator_data['name'],
                'department': evaluator_data['department'],
                'email': evaluator_data['email'],
                'specialization': evaluator_data.get('specialization', []),
                'certification': evaluator_data.get('certification', ''),
                'registration_date': datetime.now(),
                'is_active': True
            }
            return True
        except Exception as e:
            print(f"注册评估员失败: {e}")
            return False
    
    def create_contract(self, contract_data: Dict[str, Any]) -> Optional[str]:
        """创建合同"""
        try:
            contract_id = f"CONTRACT_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
            
            contract = Contract(
                contract_id=contract_id,
                supplier_id=contract_data['supplier_id'],
                contract_name=contract_data['contract_name'],
                contract_type=contract_data['contract_type'],
                start_date=contract_data['start_date'],
                end_date=contract_data['end_date'],
                contract_value=contract_data['contract_value'],
                currency=contract_data.get('currency', 'CNY'),
                status=contract_data.get('status', ContractStatus.DRAFT.value),
                payment_terms=contract_data.get('payment_terms', ''),
                delivery_terms=contract_data.get('delivery_terms', ''),
                quality_requirements=contract_data.get('quality_requirements', ''),
                penalty_clauses=contract_data.get('penalty_clauses', ''),
                renewal_terms=contract_data.get('renewal_terms', ''),
                created_by=contract_data['created_by'],
                file_path=contract_data.get('file_path', ''),
                notes=contract_data.get('notes', ''),
                auto_renewal=contract_data.get('auto_renewal', False),
                renewal_notice_days=contract_data.get('renewal_notice_days', 30)
            )
            
            self.contracts[contract_id] = contract
            return contract_id
            
        except Exception as e:
            print(f"创建合同失败: {e}")
            return None
    
    def update_contract_status(self, contract_id: str, status: str, notes: str = "") -> bool:
        """更新合同状态"""
        if contract_id not in self.contracts:
            return False
        
        try:
            contract = self.contracts[contract_id]
            contract.status = status
            if notes:
                contract.notes += f"\n{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}: {notes}"
            return True
        except Exception as e:
            print(f"更新合同状态失败: {e}")
            return False
    
    def get_contract_renewal_alerts(self, days_ahead: int = 30) -> List[Dict[str, Any]]:
        """获取合同续约提醒"""
        alerts = []
        current_date = datetime.now()
        alert_date = current_date + timedelta(days=days_ahead)
        
        for contract in self.contracts.values():
            if (contract.status == ContractStatus.ACTIVE.value and 
                contract.end_date <= alert_date and 
                contract.end_date > current_date):
                
                days_to_expiry = (contract.end_date - current_date).days
                supplier = self.suppliers.get(contract.supplier_id)
                
                alerts.append({
                    'contract_id': contract.contract_id,
                    'contract_name': contract.contract_name,
                    'supplier_id': contract.supplier_id,
                    'supplier_name': supplier.name if supplier else 'Unknown',
                    'end_date': contract.end_date,
                    'days_to_expiry': days_to_expiry,
                    'contract_value': contract.contract_value,
                    'auto_renewal': contract.auto_renewal,
                    'renewal_notice_days': contract.renewal_notice_days,
                    'priority': 'high' if days_to_expiry <= 7 else 'medium' if days_to_expiry <= 15 else 'low'
                })
        
        # 按到期时间排序
        alerts.sort(key=lambda x: x['days_to_expiry'])
        return alerts
    
    def evaluate_supplier_performance(self, evaluation_data: Dict[str, Any]) -> Optional[str]:
        """评估供应商绩效"""
        try:
            record_id = f"PERF_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
            
            # 计算评分
            score = self._calculate_performance_score(
                evaluation_data['metric_value'],
                evaluation_data['target_value'],
                evaluation_data['metric_type']
            )
            
            record = PerformanceRecord(
                record_id=record_id,
                supplier_id=evaluation_data['supplier_id'],
                evaluation_period=evaluation_data['evaluation_period'],
                metric_type=evaluation_data['metric_type'],
                metric_value=evaluation_data['metric_value'],
                target_value=evaluation_data['target_value'],
                unit=evaluation_data.get('unit', ''),
                score=score,
                comments=evaluation_data.get('comments', ''),
                evaluator=evaluation_data['evaluator'],
                supporting_data=evaluation_data.get('supporting_data', {})
            )
            
            self.performance_records.append(record)
            
            # 根据绩效更新供应商分类
            self._update_supplier_category_by_performance(evaluation_data['supplier_id'])
            
            return record_id
            
        except Exception as e:
            print(f"评估供应商绩效失败: {e}")
            return None
    
    def create_risk_assessment(self, risk_data: Dict[str, Any]) -> Optional[str]:
        """创建风险评估"""
        try:
            assessment_id = f"RISK_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
            
            assessment = RiskAssessment(
                assessment_id=assessment_id,
                supplier_id=risk_data['supplier_id'],
                risk_category=risk_data['risk_category'],
                risk_description=risk_data['risk_description'],
                risk_level=risk_data['risk_level'],
                probability=risk_data['probability'],
                impact=risk_data['impact'],
                mitigation_measures=risk_data.get('mitigation_measures', []),
                responsible_person=risk_data['responsible_person'],
                review_date=risk_data.get('review_date'),
                status=risk_data.get('status', 'open')
            )
            
            self.risk_assessments.append(assessment)
            
            # 如果是高风险，自动更新供应商状态
            if assessment.risk_level in [RiskLevel.HIGH.value, RiskLevel.CRITICAL.value]:
                self._handle_high_risk_supplier(risk_data['supplier_id'], assessment)
            
            return assessment_id
            
        except Exception as e:
            print(f"创建风险评估失败: {e}")
            return None
    
    def update_risk_status(self, assessment_id: str, status_data: Dict[str, Any]) -> bool:
        """更新风险状态"""
        try:
            assessment = next(
                (r for r in self.risk_assessments if r.assessment_id == assessment_id),
                None
            )
            
            if not assessment:
                return False
            
            assessment.status = status_data['status']
            
            if 'mitigation_measures' in status_data:
                assessment.mitigation_measures = status_data['mitigation_measures']
            
            if 'review_date' in status_data:
                assessment.review_date = status_data['review_date']
            
            return True
            
        except Exception as e:
            print(f"更新风险状态失败: {e}")
            return False
    
    def get_supplier_performance_report(self, supplier_id: str = None, 
                                      period_months: int = 12) -> Dict[str, Any]:
        """获取供应商绩效报告"""
        try:
            cutoff_date = datetime.now() - timedelta(days=period_months * 30)
            
            # 筛选记录
            if supplier_id:
                records = [
                    r for r in self.performance_records
                    if r.supplier_id == supplier_id and r.evaluation_date >= cutoff_date
                ]
                suppliers_to_analyze = [supplier_id] if supplier_id in self.suppliers else []
            else:
                records = [
                    r for r in self.performance_records
                    if r.evaluation_date >= cutoff_date
                ]
                suppliers_to_analyze = list(self.suppliers.keys())
            
            if not records:
                return {'message': '指定期间内没有绩效记录'}
            
            # 按供应商分组分析
            supplier_analysis = {}
            
            for sid in suppliers_to_analyze:
                supplier_records = [r for r in records if r.supplier_id == sid]
                if not supplier_records:
                    continue
                
                supplier = self.suppliers[sid]
                
                # 按指标类型分析
                metrics_analysis = {}
                for metric_type in PerformanceMetric:
                    metric_records = [r for r in supplier_records if r.metric_type == metric_type.value]
                    if metric_records:
                        scores = [r.score for r in metric_records]
                        metrics_analysis[metric_type.value] = {
                            'average_score': statistics.mean(scores),
                            'latest_score': metric_records[-1].score,
                            'trend': self._calculate_trend([r.score for r in sorted(metric_records, key=lambda x: x.evaluation_date)]),
                            'evaluation_count': len(metric_records)
                        }
                
                # 计算综合评分
                all_scores = [r.score for r in supplier_records]
                overall_score = statistics.mean(all_scores) if all_scores else 0
                
                supplier_analysis[sid] = {
                    'supplier_info': {
                        'name': supplier.name,
                        'category': supplier.category,
                        'status': supplier.status
                    },
                    'overall_score': overall_score,
                    'total_evaluations': len(supplier_records),
                    'metrics_analysis': metrics_analysis,
                    'performance_grade': self._get_performance_grade(overall_score),
                    'improvement_areas': self._identify_improvement_areas(metrics_analysis)
                }
            
            # 生成汇总统计
            summary_stats = {
                'total_suppliers_evaluated': len(supplier_analysis),
                'total_evaluations': len(records),
                'average_overall_score': statistics.mean([s['overall_score'] for s in supplier_analysis.values()]) if supplier_analysis else 0,
                'top_performers': self._get_top_performers(supplier_analysis, 5),
                'underperformers': self._get_underperformers(supplier_analysis, 5),
                'category_performance': self._analyze_category_performance(supplier_analysis)
            }
            
            return {
                'report_period': f'{period_months}个月',
                'generated_date': datetime.now(),
                'summary_statistics': summary_stats,
                'supplier_analysis': supplier_analysis,
                'recommendations': self._generate_performance_recommendations(supplier_analysis)
            }
            
        except Exception as e:
            print(f"生成绩效报告失败: {e}")
            return {'error': str(e)}
    
    def get_risk_management_dashboard(self) -> Dict[str, Any]:
        """获取风险管理仪表板"""
        try:
            current_date = datetime.now()
            
            # 风险统计
            total_risks = len(self.risk_assessments)
            open_risks = len([r for r in self.risk_assessments if r.status == 'open'])
            
            # 按风险等级分类
            risk_by_level = {}
            for level in RiskLevel:
                count = len([r for r in self.risk_assessments if r.risk_level == level.value and r.status == 'open'])
                risk_by_level[level.value] = count
            
            # 按风险类别分类
            risk_by_category = {}
            for risk in self.risk_assessments:
                if risk.status == 'open':
                    category = risk.risk_category
                    risk_by_category[category] = risk_by_category.get(category, 0) + 1
            
            # 需要审查的风险
            risks_for_review = [
                r for r in self.risk_assessments
                if r.status == 'open' and r.review_date <= current_date
            ]
            
            # 高风险供应商
            high_risk_suppliers = []
            for supplier_id in self.suppliers.keys():
                supplier_risks = [r for r in self.risk_assessments if r.supplier_id == supplier_id and r.status == 'open']
                high_risks = [r for r in supplier_risks if r.risk_level in [RiskLevel.HIGH.value, RiskLevel.CRITICAL.value]]
                
                if high_risks:
                    supplier = self.suppliers[supplier_id]
                    high_risk_suppliers.append({
                        'supplier_id': supplier_id,
                        'supplier_name': supplier.name,
                        'risk_count': len(high_risks),
                        'highest_risk_score': max(r.risk_score for r in high_risks),
                        'critical_risks': len([r for r in high_risks if r.risk_level == RiskLevel.CRITICAL.value])
                    })
            
            # 按风险评分排序
            high_risk_suppliers.sort(key=lambda x: x['highest_risk_score'], reverse=True)
            
            return {
                'risk_summary': {
                    'total_risks': total_risks,
                    'open_risks': open_risks,
                    'closed_risks': total_risks - open_risks,
                    'risks_for_review': len(risks_for_review)
                },
                'risk_distribution': {
                    'by_level': risk_by_level,
                    'by_category': risk_by_category
                },
                'high_risk_suppliers': high_risk_suppliers[:10],
                'urgent_actions': {
                    'risks_for_review': [asdict(r) for r in risks_for_review[:5]],
                    'critical_risks': [
                        asdict(r) for r in self.risk_assessments
                        if r.risk_level == RiskLevel.CRITICAL.value and r.status == 'open'
                    ][:5]
                },
                'risk_trends': self._analyze_risk_trends()
            }
            
        except Exception as e:
            print(f"生成风险管理仪表板失败: {e}")
            return {'error': str(e)}
    
    def export_supplier_data(self, file_path: str, data_type: str = "suppliers") -> bool:
        """导出供应商数据"""
        try:
            if data_type == "suppliers":
                data = [asdict(supplier) for supplier in self.suppliers.values()]
            elif data_type == "contracts":
                data = [asdict(contract) for contract in self.contracts.values()]
            elif data_type == "performance":
                data = [asdict(record) for record in self.performance_records]
            elif data_type == "risks":
                data = [asdict(risk) for risk in self.risk_assessments]
            else:
                return False
            
            if not data:
                return False
            
            # 导出为CSV格式
            with open(file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
                if data:
                    fieldnames = data[0].keys()
                    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                    writer.writeheader()
                    
                    for row in data:
                        # 处理日期时间字段
                        processed_row = {}
                        for key, value in row.items():
                            if isinstance(value, datetime):
                                processed_row[key] = value.strftime('%Y-%m-%d %H:%M:%S')
                            elif isinstance(value, list):
                                processed_row[key] = '; '.join(str(item) for item in value)
                            elif isinstance(value, dict):
                                processed_row[key] = json.dumps(value, ensure_ascii=False)
                            else:
                                processed_row[key] = value
                        writer.writerow(processed_row)
            
            return True
            
        except Exception as e:
            print(f"导出数据失败: {e}")
            return False
    
    # 私有辅助方法
    def _calculate_overall_score(self, supplier_id: str) -> float:
        """计算供应商综合评分"""
        supplier_records = [
            r for r in self.performance_records
            if r.supplier_id == supplier_id
        ]
        
        if not supplier_records:
            return 0.0
        
        # 获取最近6个月的记录
        cutoff_date = datetime.now() - timedelta(days=180)
        recent_records = [
            r for r in supplier_records
            if r.evaluation_date >= cutoff_date
        ]
        
        if not recent_records:
            recent_records = supplier_records[-10:]  # 取最近10条记录
        
        # 按指标类型加权计算
        weights = {
            PerformanceMetric.QUALITY.value: 0.3,
            PerformanceMetric.DELIVERY.value: 0.25,
            PerformanceMetric.COST.value: 0.2,
            PerformanceMetric.SERVICE.value: 0.15,
            PerformanceMetric.INNOVATION.value: 0.05,
            PerformanceMetric.SUSTAINABILITY.value: 0.05
        }
        
        weighted_score = 0.0
        total_weight = 0.0
        
        for metric_type, weight in weights.items():
            metric_records = [r for r in recent_records if r.metric_type == metric_type]
            if metric_records:
                avg_score = statistics.mean([r.score for r in metric_records])
                weighted_score += avg_score * weight
                total_weight += weight
        
        return weighted_score / total_weight if total_weight > 0 else 0.0
    
    def _get_key_metrics(self, supplier_id: str) -> Dict[str, Any]:
        """获取关键指标"""
        supplier_records = [
            r for r in self.performance_records
            if r.supplier_id == supplier_id
        ]
        
        key_metrics = {}
        
        for metric_type in PerformanceMetric:
            metric_records = [r for r in supplier_records if r.metric_type == metric_type.value]
            if metric_records:
                latest_record = max(metric_records, key=lambda x: x.evaluation_date)
                key_metrics[metric_type.value] = {
                    'latest_score': latest_record.score,
                    'latest_value': latest_record.metric_value,
                    'target_value': latest_record.target_value,
                    'unit': latest_record.unit,
                    'evaluation_date': latest_record.evaluation_date
                }
        
        return key_metrics
    
    def _get_overall_risk_level(self, supplier_id: str) -> str:
        """获取供应商整体风险等级"""
        supplier_risks = [
            r for r in self.risk_assessments
            if r.supplier_id == supplier_id and r.status == 'open'
        ]
        
        if not supplier_risks:
            return RiskLevel.LOW.value
        
        # 如果有任何严重风险，整体风险为严重
        if any(r.risk_level == RiskLevel.CRITICAL.value for r in supplier_risks):
            return RiskLevel.CRITICAL.value
        
        # 如果有高风险，整体风险为高
        if any(r.risk_level == RiskLevel.HIGH.value for r in supplier_risks):
            return RiskLevel.HIGH.value
        
        # 如果有中等风险，整体风险为中等
        if any(r.risk_level == RiskLevel.MEDIUM.value for r in supplier_risks):
            return RiskLevel.MEDIUM.value
        
        return RiskLevel.LOW.value
    
    def _get_supplier_recommendations(self, supplier_id: str) -> List[str]:
        """获取供应商建议"""
        recommendations = []
        
        supplier = self.suppliers[supplier_id]
        overall_score = self._calculate_overall_score(supplier_id)
        risk_level = self._get_overall_risk_level(supplier_id)
        
        # 基于绩效的建议
        if overall_score < 60:
            recommendations.append("供应商绩效较低，建议加强管理和监督")
        elif overall_score < 80:
            recommendations.append("供应商绩效中等，建议制定改进计划")
        else:
            recommendations.append("供应商绩效优秀，建议考虑战略合作")
        
        # 基于风险的建议
        if risk_level == RiskLevel.CRITICAL.value:
            recommendations.append("存在严重风险，建议立即采取缓解措施")
        elif risk_level == RiskLevel.HIGH.value:
            recommendations.append("存在高风险，建议制定风险管控计划")
        
        # 基于合同的建议
        active_contracts = [
            c for c in self.contracts.values()
            if c.supplier_id == supplier_id and c.status == ContractStatus.ACTIVE.value
        ]
        
        if not active_contracts:
            recommendations.append("当前无有效合同，建议评估合作必要性")
        
        # 基于分类的建议
        if supplier.category == SupplierCategory.CONDITIONAL.value:
            recommendations.append("供应商为条件供应商，建议定期评估升级可能性")
        elif supplier.category == SupplierCategory.STRATEGIC.value:
            recommendations.append("战略供应商，建议加强长期合作关系")
        
        return recommendations
    
    def _calculate_performance_score(self, actual_value: float, target_value: float, metric_type: str) -> float:
        """计算绩效评分"""
        if target_value == 0:
            return 0.0
        
        # 根据指标类型计算评分
        if metric_type in [PerformanceMetric.QUALITY.value, PerformanceMetric.SERVICE.value]:
            # 质量和服务：实际值越高越好
            ratio = actual_value / target_value
            score = min(100, ratio * 100)
        elif metric_type == PerformanceMetric.COST.value:
            # 成本：实际值越低越好
            if actual_value <= target_value:
                score = 100
            else:
                ratio = target_value / actual_value
                score = max(0, ratio * 100)
        elif metric_type == PerformanceMetric.DELIVERY.value:
            # 交付：准时率，实际值越高越好
            ratio = actual_value / target_value
            score = min(100, ratio * 100)
        else:
            # 其他指标：默认处理
            ratio = actual_value / target_value
            score = min(100, ratio * 100)
        
        return max(0, min(100, score))
    
    def _update_supplier_category_by_performance(self, supplier_id: str):
        """根据绩效更新供应商分类"""
        overall_score = self._calculate_overall_score(supplier_id)
        supplier = self.suppliers[supplier_id]
        
        # 根据评分调整分类
        if overall_score >= 90:
            new_category = SupplierCategory.STRATEGIC.value
        elif overall_score >= 80:
            new_category = SupplierCategory.PREFERRED.value
        elif overall_score >= 70:
            new_category = SupplierCategory.APPROVED.value
        elif overall_score >= 60:
            new_category = SupplierCategory.CONDITIONAL.value
        else:
            new_category = SupplierCategory.DEVELOPMENT.value
        
        # 只有在分类需要调整时才更新
        if supplier.category != new_category:
            supplier.category = new_category
            supplier.last_updated = datetime.now()
    
    def _handle_high_risk_supplier(self, supplier_id: str, assessment: RiskAssessment):
        """处理高风险供应商"""
        supplier = self.suppliers[supplier_id]
        
        if assessment.risk_level == RiskLevel.CRITICAL.value:
            # 严重风险：暂停供应商
            supplier.status = SupplierStatus.SUSPENDED.value
        elif assessment.risk_level == RiskLevel.HIGH.value:
            # 高风险：标记为审查中
            supplier.status = SupplierStatus.UNDER_REVIEW.value
        
        supplier.last_updated = datetime.now()
    
    def _calculate_trend(self, values: List[float]) -> str:
        """计算趋势"""
        if len(values) < 2:
            return 'stable'
        
        # 简单线性趋势计算
        x = list(range(len(values)))
        n = len(values)
        
        sum_x = sum(x)
        sum_y = sum(values)
        sum_xy = sum(x[i] * values[i] for i in range(n))
        sum_x2 = sum(xi * xi for xi in x)
        
        slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x * sum_x)
        
        if slope > 0.5:
            return 'increasing'
        elif slope < -0.5:
            return 'decreasing'
        else:
            return 'stable'
    
    def _get_performance_grade(self, score: float) -> str:
        """获取绩效等级"""
        if score >= 90:
            return 'A'
        elif score >= 80:
            return 'B'
        elif score >= 70:
            return 'C'
        elif score >= 60:
            return 'D'
        else:
            return 'F'
    
    def _identify_improvement_areas(self, metrics_analysis: Dict[str, Any]) -> List[str]:
        """识别改进领域"""
        improvement_areas = []
        
        for metric_type, analysis in metrics_analysis.items():
            if analysis['average_score'] < 70:
                improvement_areas.append(metric_type)
        
        return improvement_areas
    
    def _get_top_performers(self, supplier_analysis: Dict[str, Any], count: int) -> List[Dict[str, Any]]:
        """获取表现最佳的供应商"""
        sorted_suppliers = sorted(
            supplier_analysis.items(),
            key=lambda x: x[1]['overall_score'],
            reverse=True
        )
        
        return [
            {
                'supplier_id': sid,
                'supplier_name': analysis['supplier_info']['name'],
                'overall_score': analysis['overall_score'],
                'performance_grade': analysis['performance_grade']
            }
            for sid, analysis in sorted_suppliers[:count]
        ]
    
    def _get_underperformers(self, supplier_analysis: Dict[str, Any], count: int) -> List[Dict[str, Any]]:
        """获取表现较差的供应商"""
        sorted_suppliers = sorted(
            supplier_analysis.items(),
            key=lambda x: x[1]['overall_score']
        )
        
        return [
            {
                'supplier_id': sid,
                'supplier_name': analysis['supplier_info']['name'],
                'overall_score': analysis['overall_score'],
                'performance_grade': analysis['performance_grade'],
                'improvement_areas': analysis['improvement_areas']
            }
            for sid, analysis in sorted_suppliers[:count]
        ]
    
    def _analyze_category_performance(self, supplier_analysis: Dict[str, Any]) -> Dict[str, Any]:
        """分析各分类供应商的绩效"""
        category_stats = {}
        
        for category in SupplierCategory:
            category_suppliers = [
                analysis for analysis in supplier_analysis.values()
                if analysis['supplier_info']['category'] == category.value
            ]
            
            if category_suppliers:
                scores = [s['overall_score'] for s in category_suppliers]
                category_stats[category.value] = {
                    'supplier_count': len(category_suppliers),
                    'average_score': statistics.mean(scores),
                    'min_score': min(scores),
                    'max_score': max(scores)
                }
        
        return category_stats
    
    def _generate_performance_recommendations(self, supplier_analysis: Dict[str, Any]) -> List[str]:
        """生成绩效改进建议"""
        recommendations = []
        
        # 分析整体绩效
        all_scores = [s['overall_score'] for s in supplier_analysis.values()]
        if all_scores:
            avg_score = statistics.mean(all_scores)
            
            if avg_score < 70:
                recommendations.append("整体供应商绩效偏低，建议加强供应商管理和培训")
            
            # 分析改进领域
            all_improvement_areas = []
            for analysis in supplier_analysis.values():
                all_improvement_areas.extend(analysis['improvement_areas'])
            
            if all_improvement_areas:
                from collections import Counter
                common_areas = Counter(all_improvement_areas).most_common(3)
                for area, count in common_areas:
                    recommendations.append(f"多个供应商在{area}方面需要改进，建议制定专项提升计划")
        
        return recommendations
    
    def _analyze_risk_trends(self) -> Dict[str, Any]:
        """分析风险趋势"""
        # 按月统计风险数量
        monthly_risks = {}
        current_date = datetime.now()
        
        for i in range(12):
            month_start = current_date.replace(day=1) - timedelta(days=i*30)
            month_end = month_start + timedelta(days=30)
            month_key = month_start.strftime('%Y-%m')
            
            month_risks = [
                r for r in self.risk_assessments
                if month_start <= r.assessment_date < month_end
            ]
            
            monthly_risks[month_key] = {
                'total_risks': len(month_risks),
                'critical_risks': len([r for r in month_risks if r.risk_level == RiskLevel.CRITICAL.value]),
                'high_risks': len([r for r in month_risks if r.risk_level == RiskLevel.HIGH.value])
            }
        
        return {
            'monthly_statistics': monthly_risks,
            'trend_analysis': '风险数量趋势分析需要更多历史数据'
        }